package com.lishem.nettymain.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class MyChannelHandler extends ChannelInboundHandlerAdapter {

    /***
     * 读取客户端传入的数据
     * @param ctx:上下文对象
     * @param msg:客户端传入的数据
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        String content = byteBuf.toString(CharsetUtil.UTF_8);
        System.out.println("客户端数据：" + content);

        // 响应数据给客户端--->出站
        ctx.writeAndFlush(Unpooled.copiedBuffer("Success!", CharsetUtil.UTF_8));
        // 手动释放数据
        //ReferenceCountUtil.release(byteBuf);
        // 需要回收的资源下沉
        ctx.fireChannelRead(msg);
    }

    /***
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
